package com.spzx.order.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.DateUtils;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.order.domain.OrderInfo;
import com.spzx.order.domain.OrderItem;
import com.spzx.order.domain.OrderLog;
import com.spzx.order.form.OrderForm;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.order.service.IOrderInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.order.vo.TradeVo;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.SkuPriceVo;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.api.domain.UserAddress;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2025-02-26
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {

    @Autowired
    private RemoteCartService remoteCartService;

    @Autowired
    private RemoteProductService remoteProductService;

    @Autowired
    private RemoteUserAddressService remoteUserAddressService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderLogMapper orderLogMapper;

    @Override
    public TradeVo orderTradeData() {
        //获取当前登陆用户id
        Long userId = SecurityContextHolder.getUserId();
        R<List<CartInfo>> cartCheckedList = remoteCartService.getCartCheckedList(SecurityConstants.INNER);
        List<CartInfo> cartInfoList = cartCheckedList.getData();
        if (CollectionUtils.isEmpty(cartInfoList)){
            throw new ServiceException("购物车为空");
        }
        //将集合泛型从购物车改为订单明细
        List<OrderItem> orderItemList = null;
        BigDecimal totalAmount = new BigDecimal(0);
        if (!CollectionUtils.isEmpty(cartInfoList)){
            orderItemList = cartInfoList.stream().map(cartInfo -> {
                OrderItem orderItem = new OrderItem();
                BeanUtils.copyProperties(cartInfo,orderItem);
                orderItem.setSkuNum(cartInfo.getSkuNum());
                return orderItem;
            }).collect(Collectors.toList());
        }
        //订单总金额
        totalAmount = orderItemList.stream()
                .map(orderItem -> {
                    return orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum()));
                }).reduce(BigDecimal.ZERO, BigDecimal::add);
        //渲染订单确认页面-生成用户流水号（防止页面重复提交和页面等待超时）
        String tradeNo = this.generateTradeNo(userId);
        TradeVo tradeVo = new TradeVo();
        tradeVo.setTradeNo(tradeNo);
        tradeVo.setTotalAmount(totalAmount);
        tradeVo.setOrderItemList(orderItemList);
        return tradeVo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long submitOrder(OrderForm orderForm) {
        //1.验证流水号，避免回退造成订单重复提交或用户长时间停留在订单确认页
        String tradeNo = orderForm.getTradeNo();
        //1.1 利用lua脚本保证判断跟删除流水号原子性
        String tradeKey = "user:tradeNo:" + SecurityUtils.getUserId();
        String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                "then\n" +
                "    return redis.call(\"del\",KEYS[1])\n" +
                "else\n" +
                "    return 0\n" +
                "end";
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
        Long flag = (Long) redisTemplate.execute(redisScript, Arrays.asList(tradeKey), tradeNo);
        if (flag.intValue() == 0){
            throw new ServiceException("订单已提交，请勿重复提交");
        }
        //2.验证商品价格是否变更,如果订单明细中任意商品价格变更，业务终止
        //2.1 获取订单明细列表，获取订单中商品SKUID列表
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        if (CollectionUtils.isEmpty(orderItemList)){
            throw new ServiceException("订单明细为空");
        }
        List<Long> skuIdList = orderItemList.stream().map(OrderItem::getSkuId).collect(Collectors.toList());
        //2.2 远程调用商品服务批量获取商品最新价格，封装Map<商品ID，最新价格>方便获取某件商品价格
        R<List<SkuPriceVo>> r = remoteProductService.getSkuPriceList(skuIdList, SecurityConstants.INNER);
        if (r.getCode() == R.FAIL){
            throw new ServiceException("获取商品最新价格失败");
        }
        List<SkuPriceVo> skuPriceVoList = r.getData();
        Map<Long, BigDecimal> skuNewPriceMap = skuPriceVoList.stream()
                .collect(Collectors.toMap(SkuPriceVo::getSkuId, SkuPriceVo::getSalePrice)); //2.3 创建价格错误提示信息变量
        String priceErrorMsg = "";

        //2.4 如果价格存在变更，更新购物车中商品价格
        for (OrderItem orderItem : orderItemList) {
            //TODO BigDecimal类型比较一定要用compareTo方法，不能用equals
            if (orderItem.getSkuPrice().compareTo(skuNewPriceMap.get(orderItem.getSkuId())) != 0) {
                priceErrorMsg += orderItem.getSkuName() + "\t";
            }
        }
        //判断是否有价格变更
        if (!ObjectUtils.isEmpty(priceErrorMsg)){
            //2.4.1 通过购物车途径保存订单，远程调用购物车服务更新购物车商品价格
            if (!orderForm.getIsBuy()) {
                R<Boolean> r1 = remoteCartService.updateCartPrice(orderForm.getUserAddressId(), SecurityConstants.INNER);
                if (R.FAIL == r1.getCode()) {
                    throw new ServiceException("购物车服务更新购物车商品价格接口有误请稍后再试");
                }

            }
            //2.4.1 将错误提示信息返回给客户端
            throw new ServiceException("订单商品" + priceErrorMsg + "价格有变更，请重新下单");
        }
        //3.保存订单及订单明细列表包括订单日志
        Long orderId = this.saveOrder(orderForm);

        //4.TODO 锁定商品库存
        //5.通过购物车途径保存订单,清理购物车中选中商品
        if (!orderForm.getIsBuy()) {
            R<Boolean> r1 = remoteCartService.deleteCartCheckedList(SecurityUtils.getUserId(), SecurityConstants.INNER);
            if (R.FAIL == r1.getCode()) {
                throw new ServiceException(r1.getMsg());
            }
        }
        return orderId;
    }

    /**
     *
     * @param orderForm
     * @return
     */
    private Long saveOrder(OrderForm orderForm) {
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(SecurityUtils.getUserId());
        orderInfo.setNickName(SecurityUtils.getUsername());
        //1.1 生成全局唯一订单编号, 日期+全局唯一ID 采用MP提供的
        String today = DateUtils.getDate().replaceAll("-", "");
        String orderNo = today + IdWorker.getIdStr();
        orderInfo.setOrderNo(orderNo);
        //实时获取总价格
        //计算orderItem中商品的总价格
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        BigDecimal totalAmount = orderItemList.stream()
                .map(orderItem -> orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())))
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        orderInfo.setTotalAmount(totalAmount);
        orderInfo.setCouponAmount(new BigDecimal("0"));
        orderInfo.setOriginalTotalAmount(totalAmount);
        BigDecimal feightFee = new BigDecimal("0");
        //商品价格超过999元，免运费，否则运费6元
        if (totalAmount.compareTo(new BigDecimal("999")) > 0) {
            feightFee = new BigDecimal("0");
        } else {
            feightFee = new BigDecimal("6");
        }
        orderInfo.setFeightFee(feightFee);
        orderInfo.setOrderStatus(0);
        orderInfo.setRemark(orderForm.getRemark());
        //调用远程服务获得地址信息
        R<UserAddress> userAddress = remoteUserAddressService.getUserAddress(orderForm.getUserAddressId(), SecurityConstants.INNER);
        if (R.FAIL == userAddress.getCode()) {
            throw new ServiceException(userAddress.getMsg());
        }
        UserAddress userAddressData = userAddress.getData();
        orderInfo.setReceiverName(userAddressData.getName());
        orderInfo.setReceiverPhone(userAddressData.getPhone());
        orderInfo.setReceiverTagName(userAddressData.getTagName());
        orderInfo.setReceiverProvince(userAddressData.getProvinceCode());
        orderInfo.setReceiverCity(userAddressData.getCityCode());
        orderInfo.setReceiverDistrict(userAddressData.getDistrictCode());
        orderInfo.setReceiverAddress(userAddressData.getAddress());
        orderInfo.setReceiverAddress(userAddressData.getFullAddress());
        orderInfo.setCreateBy(SecurityUtils.getUsername());
        baseMapper.insert(orderInfo);
        Long orderId = orderInfo.getId();
        //2.保存订单明细
        for (OrderItem orderItem : orderForm.getOrderItemList()){
            orderItem.setOrderId(orderId);
            orderItem.setCreateBy(SecurityUtils.getUsername());
            orderItemMapper.insert(orderItem);

        }

        //3.记录订单日志
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderId);
        orderLog.setOperateUser(SecurityUtils.getUsername());
        orderLog.setProcessStatus(0);
        orderLog.setNote(orderForm.getRemark());
        orderLog.setCreateBy(SecurityUtils.getUsername());
        orderLogMapper.insert(orderLog);
        return orderId;
    }

    /**
     * 基于用户ID生成订单流水号
     *
     * @param userId
     * @return
     */
    private String generateTradeNo(Long userId) {
        String tradeKey = "user:tradeNo:" + userId;
        String tradeNo = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(tradeKey, tradeNo, 5, TimeUnit.MINUTES);
        return tradeNo;
    }

}
